package org.company.mars.activemq;

import javax.jms.Connection;
import javax.jms.DeliveryMode;
import javax.jms.Destination;
import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.MessageConsumer;
import javax.jms.MessageProducer;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.company.mars.util.MQUtils;

public class QueneConsumer {
	
	public void consume() throws JMSException {
		Connection connection = MQUtils.getConnection();
		connection.setClientID("client01");
		connection.start();
		boolean transacted = false;
		Session session = connection.createSession(transacted, Session.AUTO_ACKNOWLEDGE);
		Destination destination = session.createQueue("TOOL.DEFAULT");
		
		MessageProducer replayProducer = session.createProducer(destination);
		replayProducer.setDeliveryMode(DeliveryMode.NON_PERSISTENT);
		
		MessageConsumer consumer = session.createConsumer(destination);
		this.reciveAndClose(connection, session, consumer);
	}
	
	public void reciveAndClose(Connection connection,Session session,MessageConsumer consumer) throws JMSException {
		Message message = consumer.receive();
		if(message != null) {
			if(message instanceof TextMessage){
				TextMessage txtMsg = (TextMessage)message;
				System.out.println("recevie message is : " + txtMsg.getText());
			}
		}
		Boolean flag = message.getBooleanProperty("flag");
		String msg = message.getStringProperty("message");
		System.out.println("flag:=" + flag + ",msg=" + msg);
		consumer.close();
		session.close();
		connection.close();
	}
}
